package stream;

import java.io.*;
import java.util.Scanner;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * 效率较低的针对文件的内容查找
 */
@SuppressWarnings({"all"})
public class Demo6 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入要查找的文件目录: ");
        String rootPath = in.nextLine();
        String word = in.nextLine();
        // 检查是否为一个目录
        File rootFile = new File(rootPath);
        if (!rootFile.isDirectory()){
            System.out.println("输入有误!");
            return;
        }
        // 查找操作
        try {
            scanDir(rootFile, word);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            in.close();
        }
    }

    private static void scanDir(File rootFile, String word) throws IOException {
        // 先列出文件
        File[] files = rootFile.listFiles();
        if (files == null){
            // 说明是一个空目录
            return;
        }
        // 查找
        for(File f : files){
            // 读取每个文件写入stringBuilder中，再看是否包含
            if (f.isFile()){
                if (containsWord(rootFile, word)){
                    // 如果包含 则输出文件路径
                    System.out.println(f.getCanonicalPath());
                }
            }else {
                // 递归查找
                scanDir(f, word);
            }
        }
    }

    private static boolean containsWord(File rootFile, String word) {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(rootFile)) {
            char[] buffer = new char[1024];
            while (true){
                int len = reader.read(buffer);
                if (len == -1){
                    break;
                }
                // 把每一段读到的结果，放到StringBuilder中
                stringBuilder.append(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.indexOf(word) == -1;
    }
}
